// ==================== 配置区域 ====================
// 轮播图配置
const carouselImages = [
    './images/离人泪1.jpg',
    './images/离人泪2.jpg',
    './images/离人泪描述.jpg'
];

// 接口配置
const API_CONFIG = {
    baseUrl: 'http://119.91.237.179/api/v1',
    endpoints: {
        queryMarketConfig: '/index/query_product_config',
        createOrder: '/alipay/create_pay_order'
    }
};

// 业务参数配置
const BUSINESS_PARAMS = {
    goodsId: '9890002',
};

// 全局数据存储
let globalData = {
    goods: null,
    teamList: null,
    currentOrderInfo: null, // 存储当前下单信息
    isGroupBuyConfig: 0 // 是否配置了团购活动，0-否，1-是
};

// ==================== Cookie 操作工具 ====================
const CookieManager = {
    // 设置 Cookie
    set(name, value, days = 7, path = '/') {
        const date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        const expires = "expires=" + date.toUTCString();
        document.cookie = `${name}=${value}; ${expires}; path=${path}`;
    },

    // 获取 Cookie
    get(name) {
        const cookies = document.cookie.split(";").map(cookie => cookie.trim());
        const targetCookie = cookies.find(cookie => cookie.startsWith(`${name}=`));
        if (targetCookie) {
            return targetCookie.split("=")[1]; // 返回cookie值
        }
        return null;
    },

    // 删除 Cookie
    delete(name, path = '/') {
        document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${path};`;
    }
};

// ==================== 登录管理 ====================
const LoginManager = {
    // 检查是否已登录
    isLoggedIn() {
        const openIdToken = CookieManager.get('openIdToken');
        return openIdToken !== null && openIdToken !== '';
    },

    // 获取用户ID（openIdToken）
    getUserId() {
        const openIdToken = CookieManager.get('openIdToken');
        return openIdToken || null;
    },

    // 获取用户信息
    getUserInfo() {
        return {
            userId: this.getUserId()
        };
    },

    // 跳转到登录页
    redirectToLogin() {
        console.log('用户未登录，跳转到登录页');
        window.location.href = 'login.html';
    }
};

// ==================== 需要登录的操作处理 ====================
function requireLogin(action) {
    if (LoginManager.isLoggedIn()) {
        const userId = LoginManager.getUserId();
        console.log('用户已登录, openIdToken:', userId);
        action(userId);
    } else {
        console.log('用户未登录，跳转到登录页');
        LoginManager.redirectToLogin();
    }
}

// ==================== 工具函数 ====================
// 显示提示弹窗
function showAlert(message) {
    alert(message);
}

// 在当前页面提交支付宝表单
function openAlipayPage(htmlContent) {
    try {
        // 创建一个临时的 div 来解析 HTML
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = htmlContent;

        // 获取表单元素
        const form = tempDiv.querySelector('form');

        if (form) {
            // 设置表单在新窗口打开
            form.target = '_blank';

            // 将表单添加到当前页面（隐藏）
            form.style.display = 'none';
            document.body.appendChild(form);

            // 提交表单
            form.submit();

            // 提交后移除表单
            setTimeout(() => {
                document.body.removeChild(form);
            }, 1000);
        } else {
            throw new Error('未找到支付表单');
        }
    } catch (error) {
        console.error('打开支付页面失败:', error);
        showAlert('打开支付页面失败，请重试');
    }
}


// ==================== API 调用 ====================
const API = {
    // 获取商品页信息
    async queryMarketConfig(userId = null) {
        const params = {
            productId: BUSINESS_PARAMS.goodsId
        };

        // 只有用户登录时才传userId
        if (userId) {
            params.userId = userId;
        }

        try {
            const response = await fetch(API_CONFIG.baseUrl + API_CONFIG.endpoints.queryMarketConfig, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            });

            const result = await response.json();

            if (result.code === '0000') {
                return result.data;
            } else {
                throw new Error(result.message || '获取商品信息失败');
            }
        } catch (error) {
            console.error('获取商品信息失败:', error);
            showAlert('获取商品信息失败: ' + error.message);
            return null;
        }
    },

    // 创建订单
    async createOrder(userId, options = {}) {
        const { activityId = null, teamId = null, isGroupBuy = false } = options;

        const params = {
            userId: userId,
            productId: BUSINESS_PARAMS.goodsId,
            groupBuy: isGroupBuy
        };

        // 如果是团购商品，需要传入 activityId
        if (isGroupBuy && activityId) {
            params.activityId = activityId;
        }

        // 如果有 teamId，说明是参与已有拼团
        if (teamId) {
            params.teamId = teamId;
            console.log(`参与已有拼团，teamId: ${teamId}`);
        } else if (isGroupBuy) {
            console.log('发起新的拼团');
        } else {
            console.log('单独购买');
        }

        console.log('创建订单参数:', params);

        try {
            const response = await fetch(API_CONFIG.baseUrl + API_CONFIG.endpoints.createOrder, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            });

            const result = await response.json();

            if (result.code === '0000') {
                return result.data; // 返回支付宝HTML表单
            } else {
                throw new Error(result.message || '创建订单失败');
            }
        } catch (error) {
            console.error('创建订单失败:', error);
            showAlert('创建订单失败: ' + error.message);
            return null;
        }
    }
};

// ==================== 页面初始化 ====================
// 加载并渲染商品信息
async function loadAndRenderProductInfo() {
    // 获取用户ID（如果已登录）
    const userId = LoginManager.getUserId();
    const data = await API.queryMarketConfig(userId);

    if (!data) {
        return;
    }

    // 保存数据到全局
    globalData.goods = data.goods;
    globalData.teamList = data.groupBuyTeamList || [];
    globalData.isGroupBuyConfig = data.isGroupBuyConfig || 0;

    console.log('商品配置信息:', {
        isGroupBuyConfig: globalData.isGroupBuyConfig,
        teamListCount: globalData.teamList.length
    });

    // 渲染商品信息
    renderProductInfo();

    // 根据 isGroupBuyConfig 决定是否显示团购相关内容
    if (globalData.isGroupBuyConfig === 1) {
        // 显示团购列表区域
        document.getElementById('groupBuySection').style.display = 'block';
        // 显示拼团购买按钮
        document.getElementById('buyGroupBtn').style.display = 'inline-block';
        // 渲染团购列表
        renderGroupBuyList();
    } else {
        // 隐藏团购列表区域
        document.getElementById('groupBuySection').style.display = 'none';
        // 隐藏拼团购买按钮
        document.getElementById('buyGroupBtn').style.display = 'none';
    }
}

// 渲染商品信息
function renderProductInfo() {
    if (!globalData.goods) {
        return;
    }

    const goods = globalData.goods;
    const isLoggedIn = LoginManager.isLoggedIn();

    document.getElementById('productTitle').textContent = goods.goodsName || '商品名称';

    // 根据是否有团购活动显示不同的价格
    if (globalData.isGroupBuyConfig === 1) {
        // 团购活动时，显示优惠后价格和原价
        document.getElementById('discountPrice').textContent = `¥${(goods.payPrice || 0).toFixed(2)}`;
        document.getElementById('originalPrice').textContent = `¥${(goods.originalPrice || 0).toFixed(2)}`;
        document.getElementById('originalPrice').style.display = 'inline';
    } else {
        // 无团购活动时，只显示原价
        document.getElementById('discountPrice').textContent = `¥${(goods.originalPrice || 0).toFixed(2)}`;
        document.getElementById('originalPrice').style.display = 'none';
    }

    // 显示/隐藏登录提示
    const loginTip = document.getElementById('loginTip');
    if (!isLoggedIn && globalData.isGroupBuyConfig === 1) {
        loginTip.style.display = 'block';
    } else {
        loginTip.style.display = 'none';
    }

    // 更新底部按钮文案
    document.getElementById('buyAloneBtn').textContent = `单独购买(¥${(goods.originalPrice || 0).toFixed(2)})`;

    if (globalData.isGroupBuyConfig === 1) {
        document.getElementById('buyGroupBtn').textContent = `拼团购买(¥${(goods.payPrice || 0).toFixed(2)})`;
    }
}

// 渲染团购列表
function renderGroupBuyList() {
    const container = document.getElementById('groupBuySection');
    container.innerHTML = '';

    // 如果没有团购列表
    if (!globalData.teamList || globalData.teamList.length === 0) {
        container.innerHTML = `
            <div class="empty-team-card">
                <div class="empty-team-text">当前商品暂无拼团组队，快发起团购吧！</div>
            </div>
        `;
        return;
    }

    globalData.teamList.forEach((group, index) => {
        const remainingCount = group.targetCount - group.lockCount;
        const isEnded = group.validTimeCountdown === '已结束' || group.validTimeCountdown === '无效的时间';
        const isFull = remainingCount <= 0; // 新增：判断是否已满员

        const groupItem = document.createElement('div');
        groupItem.className = 'group-buy-item';

        // 根据是否结束或已满员显示不同的内容
        if (isEnded) {
            groupItem.innerHTML = `
              <div class="group-leader">
                  <div class="leader-info">
                      <div class="leader-name">${group.userId}</div>
                      <div class="group-status">
                          <span class="status-text">拼团组队已结束</span>
                          <span class="countdown ended">${group.validTimeCountdown}</span>
                      </div>
                  </div>
              </div>
              <button class="join-group-btn" disabled style="background-color: #ccc; cursor: not-allowed;">参与拼团</button>
            `;
        } else if (isFull) {
            // 新增：已满员的情况
            groupItem.innerHTML = `
              <div class="group-leader">
                  <div class="leader-info">
                      <div class="leader-name">${group.userId}</div>
                      <div class="group-status">
                          <span class="status-text">拼团组队已满员</span>
                          <span class="countdown" data-countdown="${group.validTimeCountdown}" data-index="${index}">${group.validTimeCountdown}</span>
                      </div>
                  </div>
              </div>
              <button class="join-group-btn" disabled style="background-color: #ccc; cursor: not-allowed;">参与拼团</button>
            `;
        } else {
            groupItem.innerHTML = `
              <div class="group-leader">
                  <div class="leader-info">
                      <div class="leader-name">${group.userId}</div>
                      <div class="group-status">
                          <span class="status-text">拼团中，组队仅剩<span class="remaining-count">${remainingCount}</span>人，拼团即将结束</span>
                          <span class="countdown" data-countdown="${group.validTimeCountdown}" data-index="${index}">${group.validTimeCountdown}</span>
                      </div>
                  </div>
              </div>
              <button class="join-group-btn" 
                      data-out-trade-no="${group.outTradeNo}" 
                      data-team-id="${group.teamId}">参与拼团</button>
            `;
        }

        container.appendChild(groupItem);
    });

    // 初始化倒计时（只初始化未结束的）
    initCountdowns();
}

// ==================== 轮播图功能 ====================
class Carousel {
    constructor() {
        this.track = document.getElementById('carouselTrack');
        this.indicatorsContainer = document.getElementById('carouselIndicators');
        this.currentIndex = 0;
        this.autoPlayInterval = null;
        this.items = [];
        this.indicators = [];

        this.init();
    }

    init() {
        this.createCarouselItems();
        this.createIndicators();
        this.startAutoPlay();
    }

    createCarouselItems() {
        this.track.innerHTML = '';
        carouselImages.forEach((imgSrc, index) => {
            const item = document.createElement('div');
            item.className = `carousel-item ${index === 0 ? 'active' : ''}`;
            item.innerHTML = `<img src="${imgSrc}" alt="商品图片${index + 1}">`;
            this.track.appendChild(item);
        });
        this.items = this.track.querySelectorAll('.carousel-item');
    }

    createIndicators() {
        this.indicatorsContainer.innerHTML = '';
        carouselImages.forEach((_, index) => {
            const indicator = document.createElement('div');
            indicator.className = `indicator ${index === 0 ? 'active' : ''}`;
            indicator.addEventListener('click', () => this.goToSlide(index));
            this.indicatorsContainer.appendChild(indicator);
        });
        this.indicators = this.indicatorsContainer.querySelectorAll('.indicator');
    }

    goToSlide(index) {
        this.items[this.currentIndex].classList.remove('active');
        this.indicators[this.currentIndex].classList.remove('active');

        this.currentIndex = index;

        this.items[this.currentIndex].classList.add('active');
        this.indicators[this.currentIndex].classList.add('active');
    }

    nextSlide() {
        const nextIndex = (this.currentIndex + 1) % this.items.length;
        this.goToSlide(nextIndex);
    }

    startAutoPlay() {
        this.autoPlayInterval = setInterval(() => {
            this.nextSlide();
        }, 3000);
    }

    stopAutoPlay() {
        if (this.autoPlayInterval) {
            clearInterval(this.autoPlayInterval);
        }
    }
}

// ==================== 倒计时功能 ====================
class CountdownTimer {
    constructor(element, countdownStr, index) {
        this.element = element;
        this.countdownStr = countdownStr; // 格式: "HH:MM:SS"
        this.index = index;
        this.timer = null;

        // 检查是否为特殊状态
        if (countdownStr === '已结束' || countdownStr === '无效的时间') {
            this.element.textContent = countdownStr;
            this.element.classList.add('ended');
            return;
        }

        this.remainingSeconds = this.parseCountdown(countdownStr);

        // 如果解析后的秒数 <= 0，直接显示已结束
        if (this.remainingSeconds <= 0) {
            this.element.textContent = '已结束';
            this.element.classList.add('ended');
            return;
        }

        this.start();
    }

    parseCountdown(countdownStr) {
        // 检查是否为特殊状态字符串
        if (countdownStr === '已结束' || countdownStr === '无效的时间') {
            return 0;
        }

        const parts = countdownStr.split(':');
        if (parts.length === 3) {
            const hours = parseInt(parts[0]) || 0;
            const minutes = parseInt(parts[1]) || 0;
            const seconds = parseInt(parts[2]) || 0;
            return hours * 3600 + minutes * 60 + seconds;
        }
        return 0;
    }

    formatTime(seconds) {
        if (seconds <= 0) return '已结束';

        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;

        return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
    }

    start() {
        this.update();
        this.timer = setInterval(() => {
            this.remainingSeconds--;
            if (this.remainingSeconds <= 0) {
                this.stop();
                this.element.textContent = '已结束';
                this.element.classList.add('ended');

                // 禁用对应的按钮
                this.disableJoinButton();
            } else {
                this.update();
            }
        }, 1000);
    }

    update() {
        this.element.textContent = this.formatTime(this.remainingSeconds);
    }

    stop() {
        if (this.timer) {
            clearInterval(this.timer);
        }
    }

    // 禁用参与拼团按钮
    disableJoinButton() {
        const groupItem = this.element.closest('.group-buy-item');
        if (groupItem) {
            const joinBtn = groupItem.querySelector('.join-group-btn');
            if (joinBtn) {
                joinBtn.disabled = true;
                joinBtn.style.backgroundColor = '#ccc';
                joinBtn.style.cursor = 'not-allowed';
            }
        }
    }
}

// ==================== 初始化倒计时 ====================
let timers = [];

function initCountdowns() {
    // 清除旧的倒计时
    timers.forEach(timer => timer.stop());
    timers = [];

    const countdownElements = document.querySelectorAll('.countdown:not(.ended)');
    countdownElements.forEach(element => {
        const countdownStr = element.getAttribute('data-countdown');
        const index = parseInt(element.getAttribute('data-index'));

        // 只为有效的倒计时创建定时器
        if (countdownStr && countdownStr !== '已结束' && countdownStr !== '无效的时间') {
            const timer = new CountdownTimer(element, countdownStr, index);
            timers.push(timer);
        }
    });
}

// ==================== 事件绑定 ====================
function bindEvents() {
    // 参与拼团按钮点击事件
    document.addEventListener('click', async function(e) {
        if (e.target.classList.contains('join-group-btn') && !e.target.disabled) {
            e.preventDefault(); // 阻止默认行为

            const teamId = e.target.getAttribute('data-team-id');

            // 需要登录才能参与拼团
            requireLogin(async (userId) => {
                console.log(`用户 ${userId} 正在参与拼团，teamId: ${teamId}`);

                // 获取商品支付金额（团购价格）
                const payAmount = globalData.goods.payPrice || 0;

                // 调用创建订单接口，传入 teamId 和 activityId
                const alipayHtml = await API.createOrder(userId, {
                    activityId: globalData.goods.activityId,
                    teamId: teamId,
                    isGroupBuy: true
                });

                if (alipayHtml) {
                    // 显示支付提示弹窗
                    PaymentModal.show(payAmount);

                    // 打开支付宝支付页面
                    openAlipayPage(alipayHtml);
                }
            });
        }
    });

    // 单独购买按钮点击事件
    document.getElementById('buyAloneBtn').addEventListener('click', async function(e) {
        e.preventDefault(); // 阻止默认行为

        // 需要登录才能购买
        requireLogin(async (userId) => {
            console.log(`用户 ${userId} 正在单独购买`);

            // 获取商品支付金额（原价）
            const payAmount = globalData.goods.originalPrice || 0;

            // 调用创建订单接口，isGroupBuy 为 false
            const alipayHtml = await API.createOrder(userId, {
                isGroupBuy: false
            });

            if (alipayHtml) {
                // 显示支付提示弹窗
                PaymentModal.show(payAmount);

                // 打开支付宝支付页面
                openAlipayPage(alipayHtml);
            }
        });
    });

    // 拼团购买按钮点击事件（发起新的拼团）
    document.getElementById('buyGroupBtn').addEventListener('click', async function(e) {
        e.preventDefault(); // 阻止默认行为

        // 需要登录才能拼团购买
        requireLogin(async (userId) => {
            console.log(`用户 ${userId} 正在发起新的拼团...`);

            // 获取商品支付金额（团购价格）
            const payAmount = globalData.goods.payPrice || 0;

            // 调用创建订单接口，不传 teamId（发起新拼团）
            const alipayHtml = await API.createOrder(userId, {
                activityId: globalData.goods.activityId,
                isGroupBuy: true
            });

            if (alipayHtml) {
                // 显示支付提示弹窗
                PaymentModal.show(payAmount);

                // 打开支付宝支付页面
                openAlipayPage(alipayHtml);
            }
        });
    });
}

// ==================== 支付弹窗管理 ====================
const PaymentModal = {
    modal: null,
    overlay: null,
    amountElement: null,

    // 初始化
    init() {
        this.modal = document.getElementById('paymentModal');
        this.overlay = document.getElementById('modalOverlay');
        this.amountElement = document.getElementById('paymentAmount');

        // 绑定确定按钮事件
        document.getElementById('confirmPaymentBtn').addEventListener('click', () => {
            this.close();
        });

        // 点击遮罩层关闭弹窗
        this.overlay.addEventListener('click', () => {
            this.close();
        });
    },

    // 显示弹窗
    show(amount) {
        this.amountElement.textContent = amount.toFixed(2);
        this.modal.classList.add('show');
        // 禁止页面滚动
        document.body.style.overflow = 'hidden';
    },

    // 关闭弹窗
    close() {
        this.modal.classList.remove('show');
        // 恢复页面滚动
        document.body.style.overflow = '';
        console.log('支付弹窗已关闭');

        // 刷新页面数据
        loadAndRenderProductInfo();
    }
};

// ==================== 页面加载完成后执行 ====================
let carousel;

document.addEventListener('DOMContentLoaded', async function() {
    // 1. 初始化轮播图
    carousel = new Carousel();

    // 2. 加载并渲染商品信息和团购列表（无论是否登录都可以浏览）
    await loadAndRenderProductInfo();

    // 3. 绑定事件（点击按钮时才检查登录状态）
    bindEvents();

    // 4. 初始化支付弹窗
    PaymentModal.init();
});

// 页面卸载时清理定时器
window.addEventListener('beforeunload', () => {
    if (carousel) {
        carousel.stopAutoPlay();
    }
    timers.forEach(timer => timer.stop());
});
